/**
 * Cs340 Fatboy Mafia Team
 */
package fatboy.communication;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;


/**
 * @author Ilya Vinogradov
 *
 */
public class ResidentDatabase{
	static{
		objDatabase = new ConcurrentHashMap<ObjectID, Object>();
	}
	/**
	 * 
	 */
	private static final long serialVersionUID = 3750286121260049743L;
	private static ConcurrentMap<ObjectID,Object> objDatabase;
	public static void initialize() {
		objDatabase = new ConcurrentHashMap<ObjectID, Object>();
	}
	
	
	public static void clearDatabase(){
		objDatabase.clear();
	}
	
	/**
	 * Adds new Instance to map, object ID and object Instance
	 * 
	 * @param id
	 * @param instance
	 */
	public static void setObject(ObjectID id, Object instance){
		//System.out.println(id);
		objDatabase.put(id, instance);
	}
	
	/**
	 * Finds object from map
	 * 
	 * @param objectID
	 * @return Object associated with given ObjectID
	 */
	public static Object getObject(ObjectID objectID){
		if(objectID == null) {
			throw new IllegalArgumentException();
		}
		return objDatabase.get(objectID);
	}
	
	/**
	 * Loads the database from the local filename
	 * 
	 */
	public static synchronized void loadDatabase(String fileName){
		objDatabase = new ConcurrentHashMap<ObjectID, Object>();
		try {
			FileInputStream fis = new FileInputStream(fileName);
		    ObjectInputStream ois = new ObjectInputStream(fis);
		    
			objDatabase = ((ConcurrentMap<ObjectID,Object>) ois.readObject());
		    ois.close();
		    fis.close();
		    
		} catch (FileNotFoundException e) {
			System.out.println("ResidentDatabase: File not found: " + fileName);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**
	 * Updates map by saving map to given file;
	 */
	public static synchronized void saveDatabase(String fileName) {
		
		//Save the ObjectLoader itself
		try {
			FileOutputStream fos = new FileOutputStream(fileName);
		    ObjectOutputStream oos = new ObjectOutputStream(fos);
		    oos.writeObject(objDatabase);
		    oos.flush();
		    //oos.reset();
		    oos.close();
		    fos.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static String print(){
		return objDatabase.toString();
	}
	
	/**
	 * Removes the node from the database
	 */
	public static void remove(ObjectID id) {
		objDatabase.remove(id);
	}


}
